﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Diagnostics;

namespace Macaw.Wss4.GoogleAnalyticsSolution
{
    public abstract class GoogleAnalyticsHelper
    {
        /// <summary>
        /// This is the formatstrings for the custom property names. {0} will be replaced with the name of the zone
        /// </summary>
        private const string GATC_FORMAT = "Macaw.Wss4.GoogleAnalyticsSolution.TrackerCode.{0}";
        private const string GATEM_FORMAT = "Macaw.Wss4.GoogleAnalyticsSolution.TrackEditMode.{0}";
        private const string GATTA_FORMAT = "Macaw.Wss4.GoogleAnalyticsSolution.TrackAuthenticated.{0}";

        public static string GetStringProperty(SPSite site, SPFile file, SPUrlZone zone, bool recurse, string PropertyFormat)
        {
            string propertyname = string.Format(PropertyFormat, zone.ToString());
            try
            {
                if (file.Properties.ContainsKey(propertyname))
                {
                    return (string)file.Properties[propertyname];
                }

                if (recurse)
                {
                    return GetStringProperty(site, file.ParentFolder, zone, recurse, PropertyFormat);
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService ds = SPDiagnosticsService.Local;
                ds.WriteTrace(0, 
                    new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning), 
                    TraceSeverity.Unexpected, "Error occured retrieving \"{0}\" from file \"{1}\"\r\n{2}", 
                    new object[] { propertyname, file.ServerRelativeUrl, ex.ToString() });
            }

            return null;
        }

        public static string GetStringProperty(SPSite site, SPFolder folder, SPUrlZone zone, bool recurse, string PropertyFormat)
        {
            string propertyname = string.Format(PropertyFormat, zone.ToString());
            try
            {

                if (folder.Properties.ContainsKey(propertyname))
                {
                    return (string)folder.Properties[propertyname];
                }

                if (recurse && !folder.UniqueId.Equals( folder.ParentFolder.UniqueId ) )
                {
                    return GetStringProperty(site, folder.ParentFolder, zone, recurse, PropertyFormat);
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService ds = SPDiagnosticsService.Local;
                ds.WriteTrace(0,
                    new SPDiagnosticsCategory("GoogleAnalyticsSolution", TraceSeverity.Monitorable, EventSeverity.Warning),
                    TraceSeverity.Medium, "Error occured retrieving \"{0}\" from file \"{1}\"\r\n{2}",
                    new object[] { propertyname, folder.ServerRelativeUrl, ex.ToString() });
            }

            return null;
        }

        public static string GetStringProperty(SPSite site, SPWeb web, SPUrlZone zone, bool recurse, string PropertyFormat)
        {
            if (web == null) return null;
            return GetStringProperty(site, web.RootFolder, zone, recurse, PropertyFormat);
        }

        /// <summary>
        /// Gets the TrackerCode from the web or from the parentwebs if it's inherited.
        /// </summary>
        /// <param name="web"></param>
        /// <returns>A trackercode, null if no trackercode found, empty when trackercode was disabled</returns>
        public static string GetTrackerCode(SPSite site, SPWeb web, SPUrlZone zone, bool recurse)
        {
            if (web == null) return null;
            return GetStringProperty(site, web, zone, recurse, GATC_FORMAT);
        }

        public static string GetTrackerCode(SPSite site, SPFolder folder, SPUrlZone zone, bool recurse)
        {
            return GetStringProperty(site, folder, zone, recurse, GATC_FORMAT);
        }

        public static string GetTrackerCode(SPSite site, SPFile file, SPUrlZone zone, bool recurse)
        {
            return GetStringProperty(site, file, zone, recurse, GATC_FORMAT);
        }

        public static bool? GetTrackEditMode(SPSite site, SPWeb web, SPUrlZone zone, bool recurse)
        {
            if (web == null) return null;
            return GetTrackEditMode(site, web.RootFolder, zone, recurse);
        }

        public static bool? GetTrackEditMode(SPSite site, SPFolder folder, SPUrlZone zone, bool recurse)
        {
            bool b;
            if (bool.TryParse(GetStringProperty(site, folder, zone, recurse, GATEM_FORMAT), out b))
            {
                return b;
            }
            return null;
        }

        public static bool? GetTrackEditMode(SPSite site, SPFile file, SPUrlZone zone, bool recurse)
        {
            bool b;
            if (bool.TryParse(GetStringProperty(site, file, zone, recurse, GATEM_FORMAT), out b))
            {
                return b;
            }
            return null;
        }

        public static bool? GetTrackAuthenticated(SPSite site, SPWeb web, SPUrlZone zone, bool recurse)
        {
            if (web == null) return null;
            return GetTrackAuthenticated(site, web.RootFolder, zone, recurse);
        }

        public static bool? GetTrackAuthenticated(SPSite site, SPFolder folder, SPUrlZone zone, bool recurse)
        {
            bool b;
            if (bool.TryParse(GetStringProperty(site, folder, zone, recurse, GATTA_FORMAT), out b))
            {
                return b;
            }
            return null;
        }

        public static bool? GetTrackAuthenticated(SPSite site, SPFile file, SPUrlZone zone, bool recurse)
        {
            bool b;
            if (bool.TryParse(GetStringProperty(site, file, zone, recurse, GATTA_FORMAT), out b))
            {
                return b;
            }
            return null;
        }

        public static void SetProperty(SPFolder folder, string propertynameformat, SPUrlZone zone, string value)
        {
            string propertyname = string.Format(propertynameformat, zone.ToString());
            if (value == null)
            {
                folder.Properties.Remove(propertyname);
            }
            else
            {
                folder.Properties[propertyname] = value;
            }
        }

        public static void SetProperty(SPFile file, string propertynameformat, SPUrlZone zone, string value)
        {
            string propertyname = string.Format(propertynameformat, zone.ToString());
            if (value == null)
            {
                file.Properties.Remove(propertyname);
            }
            else
            {
                file.Properties[propertyname] = value;
            }
        }

        public static void SetTrackerCode(SPFolder folder, SPUrlZone zone, string code)
        {
            SetProperty(folder, GATC_FORMAT, zone, code);
        }

        public static void SetTrackerCode(SPFile file, SPUrlZone zone, string code)
        {
            SetProperty(file, GATC_FORMAT, zone, code);
        }

        public static void SetTrackerCode(SPWeb web, SPUrlZone zone, string code)
        {
            SetTrackerCode(web.RootFolder, zone, code);
        }

        public static void SetTrackAuthenticated(SPFolder folder, SPUrlZone zone, bool? value)
        {
            SetProperty(folder, GATTA_FORMAT, zone, value == null?null:value.Value.ToString() );
        }

        public static void SetTrackAuthenticated(SPFile file, SPUrlZone zone, bool? value)
        {
            SetProperty(file, GATTA_FORMAT, zone, value ==null ? null : value.Value.ToString());
        }

        public static void SetTrackAuthenticated(SPWeb web, SPUrlZone zone, bool? value)
        {
            SetTrackAuthenticated(web.RootFolder, zone, value);
        }

        public static void SetTrackEditMode(SPFolder folder, SPUrlZone zone, bool? value)
        {
            SetProperty(folder, GATEM_FORMAT, zone, value == null ? null : value.Value.ToString());
        }

        public static void SetTrackEditMode(SPFile file, SPUrlZone zone, bool? value)
        {
            SetProperty(file, GATEM_FORMAT, zone, value==null ? null : value.Value.ToString());
        }

        public static void SetTrackEditMode(SPWeb web, SPUrlZone zone, bool? value)
        {
            SetTrackEditMode(web.RootFolder, zone, value);
        }

    }
}
